package com.xr.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xr.pojo.User;
import com.xr.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class springSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.queryByUserName(s);
        System.out.println(user);
        if(user!=null){
            //该用户存在
            List<GrantedAuthority> list = new ArrayList<>();
            //遍历用户身上的角色和权限
            user.getRoles().forEach(role -> {
                //将角色信息添加到list集合中
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                //遍历角色拥有的权限
                role.getPermissionSets().forEach(permission -> {
                    //将权限信息添加到list集合中
                    list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                });
            });
            org.springframework.security.core.userdetails.User userSecurity = new org.springframework.security.core.userdetails.User(s,user.getPassword(),list);
            return userSecurity;
        }
        //该用户不存在
        return null;
    }
}
